package com.spstudio.iforward.front.action;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import com.spstudio.iforward.core.bean.PageObject;
import com.spstudio.iforward.core.interfaces.IQueryResult;
import com.spstudio.iforward.front.Story;
import com.spstudio.iforward.front.interfaces.IStorySessionBeanRemote;
import com.spstudio.iforward.front.qualifier.StorySessionBeanRemoteQualifier;

@Model
public class StoryAction {
	
	@Inject @StorySessionBeanRemoteQualifier IStorySessionBeanRemote storySessionBeanRemote;
	@Inject PageObject pageObject;
	
	private List<Story> storyList;
	private List<Story> hotItems;
	
	private Logger log = Logger.getLogger("StoryAction");

	@PostConstruct
	public void construct(){
		Map varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        Object pageNo = varMap.get("p");
        if (pageNo != null){
        	try{
        		int pno = Integer.parseInt((String)pageNo);
        		if (pno < 1){pno = 1;}
        		pageObject.setCurrentPageNumber(pno);
        	}catch(Exception e){
        		pageObject.setCurrentPageNumber(1);
        		log.warning("one remote client request a non-integer page number.");
        	}
        }
		loadMultiStory();
		loadHotItems();
	}
	
	private void loadHotItems(){
		hotItems = storySessionBeanRemote.loadHotItems();
	}
	
	public void loadMultiStory(){
		IQueryResult<Story> queryResult = storySessionBeanRemote.loadMultiStory(new Story(), pageObject.clone());
		pageObject.setTotalRecordsNumber(queryResult.getPageObject().getTotalRecordsNumber());
		storyList = queryResult.getResultData();
		if (storyList == null || storyList.size() == 0){
			if (pageObject.getCurrentPageNumber() > pageObject.getMaxPageNumber()){
				pageObject.setCurrentPageNumber(pageObject.getMaxPageNumber());
				loadMultiStory();
			}
		}
	}
	
	public String loadPrePage(){
		pageObject.tunePriorPageGroup();
		IQueryResult<Story> queryResult = storySessionBeanRemote.loadMultiStory(new Story(), pageObject.clone());
		pageObject.setTotalRecordsNumber(queryResult.getPageObject().getTotalRecordsNumber());
		storyList = queryResult.getResultData();
		return null;
	}
	
	public String loadNextPage(){
		pageObject.tuneNextPageGroup();
		IQueryResult<Story> queryResult = storySessionBeanRemote.loadMultiStory(new Story(), pageObject.clone());
		pageObject.setTotalRecordsNumber(queryResult.getPageObject().getTotalRecordsNumber());
		storyList = queryResult.getResultData();
		return null;
	}
	
	public List<Story> getStoryList() {
		return storyList;
	}

	public void setStoryList(List<Story> storyList) {
		this.storyList = storyList;
	}

	public List<Story> getHotItems() {
		return hotItems;
	}

	public void setHotItems(List<Story> hotItems) {
		this.hotItems = hotItems;
	}
}
